package com.garbagecan.cachestudy.job;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.util.List;

public class JobServiceImplWithCache implements JobService {

	private static CacheManager cacheManager;
	private static final Cache cache;
	private static final String JOBS_CACHE_NAME = "jobsCache";
	private static final String JOBS_CACHE_KEY = "jobs";
	
	static {
		cacheManager = new CacheManager();
		cache = new Cache(JOBS_CACHE_NAME, 1000, false, false, 5, 2);
		cacheManager.addCache(cache);
		//cacheManager.shutdown();
	}

	public boolean submitJob(Job job) {
		synchronized (cache) {
			cache.remove(JOBS_CACHE_KEY);
		}
		return BackendJobManager.submitJob(job);
	}

	public boolean killJob(Job job) {
		synchronized (cache) {
			cache.remove(JOBS_CACHE_KEY);
		}
		return BackendJobManager.killJob(job);
	}

	public List<Job> getJobs() {
		List<Job> jobs;
		synchronized (cache) {
			Element ele = cache.get(JOBS_CACHE_KEY);
			if (ele != null) {
				jobs = (List<Job>)ele.getValue();
			} else {
				System.out.println("Call backend API.");
				jobs = BackendJobManager.getJobs();
				cache.put(new Element(JOBS_CACHE_KEY, jobs));
			}
		}
		return jobs;
	}
}
